from flask import Blueprint, render_template, request, redirect, url_for
import os
import sys
from werkzeug.utils import secure_filename
import pandas as pd
import flask_excel as excel

upload_page = Blueprint("upload_page", __name__)


@upload_page.route('/bpm')
def indexbpm():
    return render_template('upload/bpm_upload.html')


@upload_page.route('/successbpm', methods=['POST'])
def successbpm():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(sys.path[0])  # 当前文件所在路径
        upload_path = os.path.join(basepath, '/www/adam/static/uploads',
                                   secure_filename("cgsq.xlsx"))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        f.save(upload_path)

        return render_template('upload/bpm_success.html', name=f.filename)


@upload_page.route('/api_upload_input_cgsq', methods=['POST', 'GET'])
def inputdatabpm():
    user = request.args.get('user')
    company = request.args.get('company')

    if user =="请选择" or  company=="请选择":
        return render_template('upload/bpm_failed.html')

    else:
        companydict = {"东杰智能科技集团股份有限公司": "101", "东杰智能科技集团股份有限公司不锈钢园区分公司": "10101", "太原东杰装备有限公司": "103"}
        userdict = {"张翼凤": "01.093", "赵军旗": "01.104", "许小玲": "01.224", "宋学强": "01.227", "姜浩文": "01.510",
                    "秦子慧": "01.732",
                    "闫于海": "01.777", "董琴": "01.230", "刘文": "01.346", "魏宗林": "01.099", "王有明": "01.511", "陈东跃": "01.244"}
        ordata = pd.read_excel(r"/www/adam/static/uploads/cgsq.xlsx", header=3,
                               dtype={"编号": str, "状态": str, "旧系统号": str, "系统编号": str, "序号": float, "名称规格": str,
                                      "图号": str,
                                      "国标材质": str, "规  格": str, "数 量": float, "单位": str, "物料代码": str, "备  注": str,
                                      "采购人员": str, "项目编号": str, "项目名称": str, "部   件": str, "外购单号": str, "计划回厂时间": str,
                                      "实际完成时间": str, "实际到货数量": float, "单   价": str, "未完成原因": str, "需支付资金额度": str,
                                      "供货商": str,
                                      "采购合同号": str, "发运时间": str, "预投状态": str, "成交价表号": str, "错误信息": str, "下发日期": str,
                                      "审核日期": str, "下发人": str, "重量": int}).set_index(
            '编号').reset_index()
        print(ordata)
        ordata.loc[ordata["物料代码"] == "0", "物料代码"] = ""
        column_names = ["FBillHead(PUR_Requisition)", "FBillTypeID", "FBillTypeID#Name", "FBillNo", "FRequestType",
                        "FApplicationOrgId", "FApplicationOrgId#Name", "*Split*1", "FEntity", "FRequireOrgId",
                        "FRequireOrgId#Name", "FMaterialId", "FMaterialId#Name", "FMaterialName", "FMaterialModel",
                        "FReqQty", "FArrivalDate", "FPurchaseOrgId", "FPurchaseOrgId#Name", "FPurchaserId",
                        "FPurchaserId#Name"]
        secend = ["*基本信息(序号)", "*(基本信息)单据类型#编码", "(基本信息)单据类型#名称", "(基本信息)单据编号", "*(基本信息)申请类型", "*(基本信息)申请组织#编码",
                  "(基本信息)申请组织#名称",
                  "间隔列", "*明细信息(序号)", "*(明细信息)需求组织#编码", "(明细信息)需求组织#名称", "*(明细信息)物料编码#编码", "(明细信息)物料编码#名称",
                  "(明细信息)物料名称", "(明细信息)规格型号", "(明细信息)申请数量", "(明细信息)到货日期", "*(明细信息)采购组织#编码",
                  "(明细信息)采购组织#名称", "(明细信息)采购员#编码", "(明细信息)采购员#名称"]
        third = ["1", "CGSQD01_SYS", "", ordata.iloc[[1], [14]].values[0][0], "标准采购申请", companydict[company], company,
                 "",
                 ordata.iloc[[0], [0]].values[0][0], companydict[company], company,
                 ordata.iloc[[0], [11]].values[0][0], ordata.iloc[[0], [5]].values[0][0],
                 ordata.iloc[[0], [5]].values[0][0], ordata.iloc[[0], [6]].values[0][0],
                 ordata.iloc[[0], [9]].values[0][0], ordata.iloc[[0], [18]].values[0][0][0:19], companydict[company],
                 company,
                 userdict[user],
                 user]
        # data = ordata.loc[:, column_names]
        list_data = []
        list_data.append(column_names)
        list_data.append(secend)

        list_data.append(third)

        for i in range(1, ordata.shape[0]):
            data_dict = ["", "", "", "", "", "", "", "", ordata.iloc[[i], [0]].values[0][0], companydict[company],
                         company,
                         ordata.iloc[[i], [11]].values[0][0],
                         ordata.iloc[[i], [5]].values[0][0],
                         ordata.iloc[[i], [5]].values[0][0], ordata.iloc[[i], [6]].values[0][0],
                         ordata.iloc[[i], [9]].values[0][0], ordata.iloc[[0], [18]].values[0][0][0:19],
                         companydict[company],
                         company,
                         userdict[user],
                         user]
            list_data.append(data_dict)

        # for i in range(1, ordata.shape[0]):
        #     data_dict = ordata.iloc[i].values.tolist()
        #     list_data.append(data_dict)

        return excel.make_response_from_array(list_data, file_type='xlsx',
                                              file_name="采购申请导出表格",
                                              sheet_name='采购申请')


